package com.zhss.demo.register.server;

/**
 * @Description: 心跳计数器
 * @auther: gubatian
 * @date: 2021/09/14
 */
public class HeartbeatMessuredRate {
    /**
     * 最后一分钟心跳次数
     */
    private long latestMinuteHeartbeatRate = 0L;
    /**
     * 最后一秒时间戳
     */
    private long latestMinuteTimestamp = System.currentTimeMillis();
    /**
     * 心跳计数时间间隔
     */
    private final Long CALCULATION_INTERVAL = 60 * 1000L;
    /**
     * 单例类
     */
    public static HeartbeatMessuredRate instance = new HeartbeatMessuredRate();
    private Daemon daemon;
    private HeartbeatMessuredRate() {
        daemon = new Daemon();
        daemon.setDaemon(true);
        daemon.setName("heartbeatMessuredRate");
        daemon.start();
    }
    public static HeartbeatMessuredRate getInstance() {
        return instance;
    }

    public synchronized void increment() {
        long currentTimestamp = System.currentTimeMillis();
        // 超过一分钟清空计数器
        if (currentTimestamp - latestMinuteTimestamp > CALCULATION_INTERVAL) {
            latestMinuteHeartbeatRate = 0L;
            latestMinuteTimestamp = System.currentTimeMillis();
            return;
        }
        latestMinuteHeartbeatRate++;
    }

    public long getLatestMinuteHeartbeatRate() {
        return latestMinuteHeartbeatRate;
    }

    private class Daemon extends Thread {
        @Override
        public void run() {
            while(true) {
                try {
                    synchronized(HeartbeatMessuredRate.class) {
                        long currentTime = System.currentTimeMillis();
                        if(currentTime - latestMinuteTimestamp > 60 * 1000) {
                            latestMinuteHeartbeatRate = 0L;
                            latestMinuteTimestamp = System.currentTimeMillis();
                        }
                    }
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
